<template>
  <div class="todo-container">
    <h1>待办事项列表</h1>

    <!-- 显示加载提示 -->
    <p v-if="loading">加载中...</p>

    <!-- 显示错误信息 -->
    <p v-if="errors" class="error">{{ errors }}</p>

    <!-- 待办事项列表 -->
    <ul v-if="!loading && !errors">
      <li v-for="todo in todos" :key="todo.id">
        <p>
          <strong>{{ todo.title }}</strong>
          <span :class="{ completed: todo.completed }">
            {{ todo.completed ? '已完成' : '未完成' }}
          </span>
        </p>
        <button @click="toggleCompleted(todo)">
          {{ todo.completed ? '取消标记' : '标记完成' }}
        </button>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { onMounted, ref } from 'vue'

const todos = ref()
const errors = ref()
const loading = ref(false)

const intaset = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 2000
})

const Axiosstodos = (method: string, url: string, params?: any, data?: any) => {
  return intaset.request({
    method,
    url,
    params,
    data
  })
}

const arr = async () => {
  loading.value = true
  errors.value = ''
  try {
    const response = await Axiosstodos('get', '/todos', { _limit: 5 })
    todos.value = response.data
    return response.data
  } catch (error) {
    errors.value = '更新任务状态失败！'
  } finally {
    loading.value = false
  }
}
onMounted(() => {
  arr()
})
const toggleCompleted = async (todo: any) => {
  let lodin = !todo.completed
  try {
    await Axiosstodos('patch', `/todos/${todo.id}`, null, {
      completed: lodin
    })
    todo.completed = lodin // 更新本地任务状态
  } catch (error) {
    errors.value = '更新任务状态失败！'
  }
}
</script>

<style lang="scss" scoped>
.todo-container {
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin-bottom: 15px;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 3px;
}

button:hover {
  background-color: #0056b3;
}

.completed {
  color: green;
  font-weight: bold;
}

.error {
  color: red;
  font-weight: bold;
}
</style>
